package com.views;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class NoScrollListView extends LinearLayout implements OnClickListener {
	private Adapter adapter;
	private OnItemClickListener lsn;
	private int divider=0;
	// private int lineHeigth;
	public NoScrollListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
		// TODO Auto-generated constructor stub
	}

	public NoScrollListView(Context context) {
		super(context);
		init();
		// TODO Auto-generated constructor stub
	}

	public void setAdapter(Adapter adapter) {
		this.adapter = adapter;
		notifyDataSetChanged();
	}

	private void init() {
		removeAllViews();
		setOrientation(LinearLayout.VERTICAL);
		divider = (int) (1 * getContext().getResources()
				.getDisplayMetrics().density);
	}

	public void notifyDataSetChanged() {
		if (adapter != null && adapter.getCount() > 0) {
			int pos = 0;
			int i = 0;
			if (getChildCount() > 0) {
				addView(getHorizontalLine());
			}
			while (pos < adapter.getCount()) {
				View v = null;
				if (getChildCount() > i) {
					v = adapter.getView(pos, getChildAt(i), this);
				} else {
					v = adapter.getView(pos, null, this);
					addView(v);
					addView(getHorizontalLine());
				}
				v.setTag(pos);
				v.setOnClickListener(this);
				pos++;
				i += 2;
			}
			while (i > 0 && getChildCount() > i - 1) {
				removeViewAt(i - 1);
			}
		} else {
			removeAllViews();
		}
	}
	public void setDivider(int divider) {
		this.divider=divider;
	}
	private ImageView getHorizontalLine() {
		ImageView horizontalLine = new ImageView(getContext());
		horizontalLine.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, divider));
		horizontalLine.setBackgroundColor(Color.parseColor("#e2e2e2"));
		return horizontalLine;
	}

	public void setOnItemClickListener(OnItemClickListener lsn) {
		this.lsn = lsn;
	}

	@Override
	public void onClick(View v) {
		if (lsn != null) {
			lsn.onItemClick(null, v, Integer.parseInt(v.getTag().toString()),
					-1);
		}

	}

}
